#!/usr/bin/env python
#coding=utf-8

from session import SessionBase
import web
from  threading import currentThread
import uuid
import thread, sys


SESSION_NAME = 'webpy_session_id'
DEFAULT_SESSION_ADDRESS = sys.platform == 'win32' and (('localhost', 8685,),) or r'/tmp/simple.session.webpy'

TERMSIGS = ()
if sys.platform != 'win32':
    from signal import signal, SIGQUIT, SIGINT, SIGTERM    
    TERMSIGS = (SIGQUIT, SIGINT,)


class Session(SessionBase):
    def __init__(self):
        self.addHook()
        super(Session, self).__init__(SESSION_NAME, DEFAULT_SESSION_ADDRESS)

    def getSessionId(self):
        sessionId = self.getCookie(self.sessionName)
        current = currentThread()
        if sessionId is None:
            if hasattr(current, 'sessionId') and current.sessionId:
                return current.sessionId
            sessionId = str(uuid.uuid4())
            current.sessionId = sessionId
            self.setCookie(self.sessionName, sessionId)
        return sessionId
    
    def clearThreadVar(self):
        currentThread().sessionId = None
        
    def hook(self, fn):
        def _fn(*args, **kwarg):
            r = fn(*args, **kwarg)
            self.clearThreadVar()
            return r
        return _fn
        
    def getCookie(self, name):
        return web.cookies().get(name)
    
    def setCookie(self, name, value):
        web.setcookie(name, value)
        
    def addHook(self):
        web.application.request = self.hook(web.application.request)
        
session = Session()

def terminate(sig, frame):
    #print 'Received Signal:', sig, currentThread(), id(currentThread()), hash(currentThread())
    try:
        import sys
        sys.exit()
    except Exception, ex:
        print type(ex), ex
        raise ex


try:
    for sig in TERMSIGS:
        signal(sig, terminate)
except:
    pass
